# -*- coding: utf-8 -*-
# @Author  : gaoyu
# @Time    : 2025/6/17 16:15
# @Function:

import json
from typing import Dict, Any, Optional
import os


def dict_to_json(data: Dict[str, Any], file_path: str,
                 ensure_ascii: bool = False, indent: int = 4,
                 create_dirs: bool = True) -> bool:
    """
    将字典数据写入JSON文件

    Args:
        data (Dict[str, Any]): 要写入的字典数据
        file_path (str): JSON文件路径
        ensure_ascii (bool): 是否确保ASCII编码，False支持中文等Unicode字符
        indent (int): JSON格式化缩进空格数，None表示紧凑格式
        create_dirs (bool): 是否自动创建目录

    Returns:
        bool: 写入成功返回True，失败返回False

    Example:
        >>> data = {"name": "张三", "age": 25, "city": "北京"}
        >>> dict_to_json(data, "output/user.json")
        True
    """
    try:
        # 如果需要，创建目录
        if create_dirs:
            dir_path = os.path.dirname(file_path)
            if dir_path and not os.path.exists(dir_path):
                os.makedirs(dir_path, exist_ok=True)

        # 写入JSON文件
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=ensure_ascii, indent=indent)

        return True

    except (TypeError, ValueError) as e:
        print(f"数据序列化错误: {e}")
        return False
    except IOError as e:
        print(f"文件写入错误: {e}")
        return False
    except Exception as e:
        print(f"未知错误: {e}")
        return False


def dict_to_json_string(data: Dict[str, Any],
                        ensure_ascii: bool = False,
                        indent: int = 4) -> Optional[str]:
    """
    将字典转换为JSON字符串

    Args:
        data (Dict[str, Any]): 要转换的字典数据
        ensure_ascii (bool): 是否确保ASCII编码
        indent (int): JSON格式化缩进空格数

    Returns:
        Optional[str]: 成功返回JSON字符串，失败返回None

    Example:
        >>> data = {"status": "success", "code": 200}
        >>> json_str = dict_to_json_string(data)
        >>> print(json_str)
    """
    try:
        return json.dumps(data, ensure_ascii=ensure_ascii, indent=indent)
    except (TypeError, ValueError) as e:
        print(f"JSON序列化错误: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    # 示例数据
    sample_data = {
        "user_info": {
            "name": "张三",
            "age": 28,
            "email": "zhangsan@example.com"
        },
        "preferences": {
            "language": "zh-CN",
            "theme": "dark",
            "notifications": True
        },
        "last_login": "2024-01-15 10:30:00",
        "scores": [95, 87, 92, 88]
    }

    # 写入JSON文件
    success = dict_to_json(sample_data, "user_data.json")
    if success:
        print("JSON文件写入成功！")
    else:
        print("JSON文件写入失败！")

    # 转换为JSON字符串
    json_string = dict_to_json_string(sample_data)
    if json_string:
        print("JSON字符串转换成功：")
        print(json_string)
